// https://aws.amazon.com/cn/s3/getting-started/
const fs = require('fs')
const mime = require('mime')
const AWS = require('aws-sdk')
const log = require('../log')
const packageJson = require('../package.json')

const UP = {}

// 检验必填配置项
UP.check = (options) => {
  log.yellow(`[${packageJson.name}] CDN >> Amazon S3 ...`)
  let isError = false
  if (!options.accessKeyId) {
    isError = true
    log.red(`[${packageJson.name}] accessKeyId not found in options.s3`)
  }
  if (!options.secretAccessKey) {
    isError = true
    log.red(`[${packageJson.name}] secretAccessKey not found in options.s3`)
  }
  if (!options.Bucket) {
    isError = true
    log.red(`[${packageJson.name}] Bucket not found in options.s3`)
  }
  if (!options.region) {
    isError = true
    log.red(`[${packageJson.name}] region not found in options.s3`)
  }
  if (isError) {
    return false
  }
  return true
}

/**
 * 上传
 * @param {String} uploadPath 上传路径
 * @param {String} localPath 本地文件路径
 * @param {Object} options 配置项 accessKeyId, secretAccessKey, Bucket, region
 */
UP.put = async(uploadPath, localPath, options) => {
  // 上传
  try {
    AWS.config.update(options)
    const S3 = await new AWS.S3()
    const result = await new Promise((resolve, reject) => {
      S3.upload({
          ...options,
          Body: fs.createReadStream(localPath),
          Key: uploadPath,
          ContentType: mime.getType(uploadPath)
        },
        (err, data) => {
        if (err == null) {
          log.green(`Upload Success => ${data.Location}`)
          resolve(null)
        } else {
          reject(err)
        }
      })
    })
    return result
  } catch (err) {
    log.red(`[${packageJson.name}] Upload Error => ${uploadPath}`)
    return err
  }
}

module.exports = UP
